<script lang="ts" setup>
import { onMounted, reactive, ref, watch, defineProps } from 'vue';
import { Form } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { getDepartmentDetailsApi, getLeaderListApi, getLeaderHeadListApi, putAdddepartmentApi, postAdddepartmentApi } from '@/common/apis/organization'
import type { FormInstance } from 'ant-design-vue';

const formRef = ref<FormInstance>();
// 储存负责人列表
const leaderListData = ref()
const labelCol = { span: 4 };
const wrapperCol = { span: 14 };
const formState = ref({
    name: '',  // 部门名称
    code: '', // 部门编码
    managerId: '',  //  部门负责人id
    introduce: '',  // 部门介绍
    pid: '', // 父级部门id
});

const props = defineProps<{
    visible: boolean;
    currentNodeId: number | null;
    actionType: string;
}>();


const emit = defineEmits(['update:visible', 'updateDepartment']);

const isModalVisible = ref(props.visible);

watch(() => props.visible, (newVal) => {
    isModalVisible.value = newVal;
});

watch(isModalVisible, (newVal) => {
    emit('update:visible', newVal);
});
const useForm = Form.useForm;


// 通用的验证函数
const validateField = async (fieldName, rule, value, callback) => {
    try {
        // 获取数据
        const response = await getLeaderListApi();
        let result = response.data.data;

        // 确保 result 是一个数组
        if (!Array.isArray(result)) {
            result = [];
        }

        // 判断是否是编辑模式
        if (props.actionType === 'edit') {
            // 编辑场景，排除自身
            result = result.filter(item => item.id !== formState.value.id);
        }

        // 检查是否存在相同的字段值
        if (result.some(item => item[fieldName] === value)) {
            message.warning('部门中已经有该' + fieldName + '了');
            callback(new Error(`部门中已经有该${fieldName}了`));
        } else {
            console.log(false, `查询结果：${fieldName} 可用`);
            callback(); // 验证通过
        }
    } catch (error) {
        console.error(`获取部门列表失败:`, error);
        callback(new Error('验证失败，请稍后重试'));
    }
};

const rules = reactive({
    name: [
        { required: true, message: '部门名称不能为空', trigger: 'change' },
        { min: 2, max: 10, message: '部门名称的长度为2-10个字符', trigger: 'blur' },
        {
            trigger: 'blur',
            validator: async (rule, value, callback) => {
                await validateField('name', rule, value, callback);
            }
        }
    ],
    code: [
        { required: true, message: '部门编码不能为空', trigger: 'blur' },
        { min: 2, max: 10, message: '部门编码的长度为2-10个字符', trigger: 'blur' },
        {
            trigger: 'blur',
            validator: async (rule, value, callback) => {
                await validateField('code', rule, value, callback);
            }
        }
    ],
    managerId: [
        { required: true, message: '部门负责人不能为空', trigger: 'blur' }
    ],
    introduce: [
        { required: true, message: '部门介绍不能为空', trigger: 'change' },
        { min: 1, max: 100, message: '部门介绍长度为1-100个字符', trigger: 'blur' }
    ]
});


// 获取部门负责人列表
const getManagerList = async () => {
    const res = await getLeaderHeadListApi()
    leaderListData.value = res.data.data
}

// 点击取消关闭弹窗
const { validate, validateInfos } = useForm(formState, rules, {
    onValidate: (...args) => console.log(...args),
});


// 获取组织的详情
const getLeaderListData = async () => {
    if (!props.currentNodeId) return
    const res = await getDepartmentDetailsApi(props.currentNodeId)
    formState.value = res.data.data
}

// 监听 currentNodeId 的变化，加载数据
watch(() => props.currentNodeId, (newVal) => {
    if (props.actionType === 'edit' && newVal) {
        getLeaderListData(); // 编辑模式，加载数据
    } else {
        formState.value = {
            name: '',  // 部门名称
            code: '', // 部门编码
            managerId: '',  //  部门负责人id
            introduce: '',  // 部门介绍
            pid: '', // 父级部门id
        }
    }
},
);


// 点击确认按钮
const onSubmit = async () => {
    // 校验表单
    await validate();
    if (props.actionType === 'add') {
        // 2. 添加子部门
        await postAdddepartmentApi({
            ...formState.value,
            pid: props.currentNodeId,
        });
        message.success('添加成功',);
    } else {
        await putAdddepartmentApi(formState.value)
        message.success('编辑成功');
    }
    // 通知父组件更新
    await getLeaderListData()
    emit('updateDepartment')
    isModalVisible.value = false;
};

onMounted(() => {
    getManagerList()
    getLeaderListData()
})

</script>

<template>
    <a-modal v-model:open="isModalVisible" :title="props.actionType == 'edit' ? '编辑部门' : '新增部门'" @ok="onSubmit">
        <a-form :label-col="labelCol" :wrapper-col="wrapperCol" ref="formRef" :model="formState" :rules="rules">
            <!-- 部门名称 -->
            <a-form-item label="部门名称:" v-bind="validateInfos.name">
                <a-input v-model:value="formState.name" placeholder="2-10个字符" />
            </a-form-item>
            <!-- 部门编码 -->
            <a-form-item label="部门编码:" v-bind="validateInfos.code">
                <a-input v-model:value="formState.code" placeholder='2-10个字符' />
            </a-form-item>
            <!-- 部门负责人 -->
            <a-form-item label="部门负责人" v-bind="validateInfos.managerId">
                <a-select v-model:value="formState.managerId" placeholder="请选择负责人">
                    <a-select-option v-for="item in leaderListData" :key="item.id">
                        {{ item.username }}
                    </a-select-option>
                </a-select>
            </a-form-item>
            <!-- 部门介绍 -->
            <a-form-item label="部门介绍" v-bind="validateInfos.introduce">
                <a-textarea placeholder='1-100个字符' v-model:value="formState.introduce" />
            </a-form-item>
        </a-form>
    </a-modal>
</template>